﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{


    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();


        }

        

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private bool  isOpen = false;

        private void button2_Click(object sender, EventArgs e)
        {

            if (!serialPort1.IsOpen)
            {
                int baud = int.Parse(cmbBaud.Text);
                serialPort1.BaudRate = baud;

                switch (cmbParity.Text)
                {
                    case "Odd":
                        serialPort1.Parity = Parity.Odd;
                        break;
                    case "Even":
                        serialPort1.Parity = Parity.Even;
                        break;
                }

                switch (cmbStopBit.Text)
                {
                    case "One":
                        serialPort1.StopBits = StopBits.One;
                        break;
                    case "Two":
                        serialPort1.StopBits = StopBits.Two;
                        break;
                }

                isOpen = true;
                serialPort1.Open();
                btnOpenClose.Text = "关闭";
            }
            else
            {
                isOpen = false;
                serialPort1.Close();
                btnOpenClose.Text = "打开";
            }

            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (isOpen)
            {
                string mes=txtSend.Text;
                
                byte[] mesByte =Encoding.ASCII.GetBytes(mes);

                serialPort1.Write(mesByte, 0, mesByte.Length);
            }

        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            

            int length = serialPort1.BytesToRead;

            byte[] recv = new byte[length];

            serialPort1.Read(recv, 0, length);

            txtRecv.Text += Encoding.ASCII.GetString(recv);


        }
    }
}
